Shader "Custom/SpriteOutline"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _BaseMap ("Texture", 2D) = "white" {}
        _OutlineColor ("Outline Color", Color) = (1,0,0,1)
        _OutlineWidth ("Outline Width", Range(0, 0.1)) = 0.05
    }
    SubShader
    {
        Tags
        {
            "RenderType"="Transparent" "Queue"="Transparent"
        }
        LOD 100

        Blend SrcAlpha OneMinusSrcAlpha
        ZWrite Off

        Pass
        {
            HLSLPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile_fragment _ALPHAPREMULTIPLY_ON
            #pragma multi_compile _ _ALPHATEST_ON

            #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"

            struct Attributes
            {
                float3 positionOS : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct Varyings
            {
                float4 positionCS : SV_POSITION;
                float2 uv : TEXCOORD0;
                UNITY_VERTEX_INPUT_INSTANCE_ID
            };

            TEXTURE2D(_BaseMap);
            SAMPLER(sampler_BaseMap);

            float4 _OutlineColor;
            float _OutlineWidth;
            float4 _BaseMap_ST;

            Varyings vert(Attributes IN)
            {
                Varyings OUT;
                UNITY_SETUP_INSTANCE_ID(IN);
                UNITY_TRANSFER_INSTANCE_ID(IN, OUT);
                OUT.positionCS = TransformObjectToHClip(IN.positionOS.xyz);
                OUT.uv = TRANSFORM_TEX(IN.uv, _BaseMap);
                return OUT;
            }

            half4 frag(Varyings IN) : SV_Target
            {
                UNITY_SETUP_INSTANCE_ID(IN);
                float2 uv = IN.uv;
                float4 col = SAMPLE_TEXTURE2D(_BaseMap, sampler_BaseMap, uv);

                float2 offsets[4] = {
                    float2(_OutlineWidth, 0),
                    float2(-_OutlineWidth, 0),
                    float2(0, _OutlineWidth),
                    float2(0, -_OutlineWidth)
                };

                float alpha = col.a;
                for (int i = 0; i < 4; i++)
                {
                    alpha = max(alpha, SAMPLE_TEXTURE2D(_BaseMap, sampler_BaseMap, uv + offsets[i]).a);
                }

                col.rgb = lerp(_OutlineColor.rgb, col.rgb, step(0.5, col.a));
                col.a = alpha;

                return col;
            }
            ENDHLSL
        }
    }
}